import json
import random

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from ihome.libs.captcha.captcha import captcha
import logging

from ihome.utils.response_code import RET

logger = logging.getLogger('django')

class ImageCodeView(View):
    """图形验证码"""

    def get(self, request):
        """
        :param request: 请求对象
        :param uuid: 当前用户的唯一id
        :return: image/jpg
        """
        uuid = request.GET.get('cur')
        # 生成图片验证码
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')

        # 图形验证码有效期，单位：秒
        # IMAGE_CODE_REDIS_EXPIRES = 300
        redis_conn.setex('img_code_%s' % uuid, 300, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpg')


class SMSCodeView(View):

    def post(self, request):
        '''
        检验图形验证码,发送短信验证码
        :param request:
        :param mobile:
        :return:
        '''
        # 1.接收参数
        # mobile = request.body.get('mobile')
        # image_code_client = request.GET.get('image_code')
        # uuid = request.GET.get('image_code_id')
        json_str = request.body
        json_str = json_str.decode()  # python3.6 无需执行此步
        req_data = json.loads(json_str)
        mobile = req_data['mobile']
        image_code_client = req_data['image_code']
        uuid = req_data['image_code_id']

        # 2.验证参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code':RET.DATAEXIST,
                                      'errmsg':'参数不能为空'})

        # 3.链接redis
        redis_conn = get_redis_connection('verify_code')

        # 4.从redis的2号库取出图形验证吗
        image_code_server = redis_conn.get('img_code_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code':RET.DBERR,
                                      'errmsg':'图形验证码失效'})

        # 5.删除redis中的图形验证吗
        try:
            redis_conn.delete('image_code_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 6.对比
        if image_code_client.lower() != image_code_server.decode().lower():
            return http.JsonResponse({'code': RET.DBERR,
                                      'errmsg': '两个图形验证码不一致'})

        # 7. 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)

        # 8. 保存到redis
        redis_conn.setex('sms_code_%s' % mobile, 300, sms_code)

        # 9. 发送(容联云)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # Celery 异步发送短信验证码
        # send_sms_code.delay(mobile, sms_code)

        # 10. 返回
        return http.JsonResponse({'code':RET.OK,
                                  'errmsg':'ok'})